package com.system.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.system.dto.UserDto;

import java.util.Date;
import java.util.Map;

public final class JWTUtils {

    private static final String SIGN = "43904327-8516-4d45-9777-6f020ecc24fb";

    public static String create(Map<String, Object> map) {
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        Object obj=null;
        for (String key :map.keySet()) {
            obj=map.get(key);
            if(obj instanceof Integer){
                builder.withClaim(key,(Integer) obj);
            } else if (obj instanceof Double) {
                builder.withClaim(key,(Double) obj);
            } else if (obj instanceof Date) {
                builder.withClaim(key,(Date) obj);
            } else if (obj instanceof String) {
                builder.withClaim(key,(String) obj);
            }else if(obj instanceof Boolean){
                builder.withClaim(key,(Boolean) obj);
            } else if (obj instanceof Long) {
                builder.withClaim(key,(Long) obj);
            }

        }
        return builder.withExpiresAt(null)//指定令牌的过期时间
                .sign(Algorithm.HMAC256(SIGN));//签发算法
    }

    public static UserDto verify(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        UserDto userDto=new UserDto();
        userDto.setId(claims.get("id").asString());
        userDto.setLoginName(claims.get("username").asString());
        userDto.setToken(token);
        return userDto;
    }


}
